<?php
/**
 * Created by JetBrains PhpStorm.
 * User: GMC02
 * Date: 10/10/13
 * Time: 2:30 PM
 * To change this template use File | Settings | File Templates.
 */

class ResetPasswordForm extends CFormModel {
    public $code;
    public $password;
    public $passwordRepeat;

    public function rules() {
        return array(
            array('password, passwordRepeat', 'required'),
            array('password', 'compare', 'compareAttribute' => 'passwordRepeat'),
            array('code, passwordRepeat', 'safe')
        );
    }

    public function validCode() {
        if(!$this->getUser()) $this->addError('code', 'Your {attribute} is not valid');
    }

    public function reset() {
        $user = $this->getUser();
        $user->password = User::model()->hashPassword($this->password);
        $user->reset_password = "";
        $user->save();

        //get email
        $emailTemplate = EmailTemplate::model()->findByAttributes(array('type' => EmailTemplateType::ResetPasswordSuccess));
        $search = array('{first_name}','{last_name}');
        $replace = array($user->first_name,$user->last_name);
        $content= str_replace($search, $replace, $emailTemplate->content);
        $mail = new EmailQueue();
        $mail->receiver = $user->email;
        $mail->subject = 'Congratz, Your password has changed successfully';
        $mail->content = $content;
        $mail->time = time();
        $mail->status = EmailQueueStatus::Queuing;
        $mail->save();

        return $user;
    }

    public function getUser() {
        return User::model()->findByAttributes(array('reset_password' => $this->code));
    }
}